package com.woniuxy.uums.service;

import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import com.baidu.aip.face.AipFace;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.codec.Base64;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.HashMap;

@Service
@Slf4j
public class BaiduFaceService {

    private AipFace client;

    @Value("${baidu.face.app-id}")
    private String appId;

    @Value("${baidu.face.api-key}")
    private String apiKey;

    @Value("${baidu.face.secret-key}")
    private String secretKey;

    @Value("${baidu.face.group-id}")
    private String groupId;

    @PostConstruct
    public void init() {
        client = new AipFace(appId, apiKey, secretKey);
        client.setConnectionTimeoutInMillis(3000);
        client.setSocketTimeoutInMillis(10000);
    }

    // 人脸搜索方法（支持URL和Base64）
    public JSONObject searchFace(String image, boolean isBase64) {
        HashMap<String, Object> options = new HashMap<>();
        options.put("quality_control", "NORMAL");
        options.put("liveness_control", "LOW");
//        options.put("max_user_num", "1");

        // 添加图片格式检测
//        String imageType = isBase64 ? "BASE64" : "URL";
        String imageType = "BASE64";

        // 如果是URL，确保是有效的图片URL
        if (!isBase64) {
            if (!image.toLowerCase().matches("^https?://.*\\.(jpg|jpeg|png|gif|bmp)(\\?.*)?$")) {
                log.warn("非标准图片URL格式: {}", image);
            }
        }
        return client.search(image, imageType, groupId, options);
    }
//    private AipFace client;
//
//    @Value("${baidu.face.app-id}")
//    private String appId;
//
//    @Value("${baidu.face.api-key}")
//    private String apiKey;
//
//    @Value("${baidu.face.secret-key}")
//    private String secretKey;
//
//    @Value("${baidu.face.group-id}")
//    private String groupId;
//
//    @PostConstruct
//    public void init() {
//        client = new AipFace(appId, apiKey, secretKey);
//        client.setConnectionTimeoutInMillis(3000);
//        client.setSocketTimeoutInMillis(10000);
//    }
//
//    public JSONObject uploadFace(String userId, String realName, String imageUrl) {
//        HashMap<String, String> options = new HashMap<>();
//        options.put("user_info", realName);
//        options.put("quality_control", "NORMAL");
//        options.put("liveness_control", "LOW");
//        options.put("action_type", "REPLACE");
//        return client.addUser(imageUrl,"URL",groupId,userId,options);
//    }


}
